<%@ page pageEncoding="UTF-8" contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/css/index.css"/>
    <script src="${pageContext.request.contextPath}/js/jquery-3.2.1.min.js"></script>
    <script src="${pageContext.request.contextPath}/js/common.js"></script>
    <script src="${pageContext.request.contextPath}/js/vue.js"></script>

    <title>资源上传</title>
</head>
<body>

<jsp:include page="common/header.jsp" />

<article>
    <!-- 网站主体 -->
    <div id="main">
        <section class="ct">
            <!-- 上传表单-->
            <div class="upload">
                <h1>上传资源<em>声明：请确保您上传的内容合法合规，涉及侵权内容将会被移除，详见<a>《爱下载资源共享规则》</a></em></h1>
                <form action="" method="post" enctype="multipart/form-data">

                    <p class="file" ref="resource">
                        <input type="file" name="resource" @change="uploadFile">

                        <span class="t1" v-show="!uploaded">点击上传、文件小于1000MB（请不要上传存在侵权的资源哦！）</span>
                        <!-- 上传后的效果 -->
                        <span class="t2" v-show="uploaded">
                            <img :src="'${pageContext.request.contextPath}/images/' + ext + '.svg'" />
                            <b v-text="resource_name"></b>
                            <progress :value="progress" max="100" v-if="show"></progress>
                            <a>重新上传</a>
                        </span>

                    </p>

                    <p>
                        <label><em>*</em>资源名称：</label>
                        <input class="upt" type="text" ref="resourcename" name="resourceName" v-model="resourceName" placeholder="请输入资源名" />
                        <em></em> <!-- 显示错误信息  -->
                    </p>

                    <p>
                        <label>资源描述：</label>
                        <textarea  class="area" v-model="resourceDesc"
                                   placeholder="简要介绍一下资源内容"></textarea>
                    </p>

                    <p>
                        <label><em>*</em>关键词：</label>
                        <span class="key-tag" ref="keywords">
								<a class="key">
                                    <span v-for="(key, index) in keywords" @click="removeKey(index)">{{key}}</span>
                                    <!-- 单击添加标签后、产生的效果 -->
                                <input type="text" v-if="showLabel" @keydown.enter="addLabel"/>
								</a>
								<span class="key-tag-msg">
									<button type="button" class="keywords add"
                                            @click="showLabel = true"
                                            v-show="keywords.length < 5">添加标签</button>
									<i class="lb">按回车键创建标签</i>
								</span>
							</span>

                        <span class="source-tag-msg">最多添加5个标签，每个标签不超过16个字</span>
                    </p>

                    <div class="source-type-div">
                        <p>
                            <label>所属分类：</label>
                            <input class="upt source-type source-type-down" type="text"
                                   :value="typeName"
                                   ref="type"
                                   name="resource_type" readonly placeholder="请选择"
                                   @click="showType ? showType=false :showType=true"/>
                        </p>
                        <div class="source-type-list" v-show="showType">
                            <select size="99999" class="one" v-model="oneTypeId" @change="showChildrenTypes">
                                <option v-for="t in types" :value="t.id">{{t.typeName}}</option>
                            </select>
                            <select class="two" size="99999" v-model="twoTypeId" @change="selectType">
                                <option v-for="c in typesChildren" :value="c.id" >{{c.typeName}}</option>
                            </select>
                        </div>
                    </div>

                    <p>
                        <label><em>*</em>资源分：</label>
                        <select class="upt" id="sel" name="score" v-model="score">
                            <option selected="selected">0</option>
                            <option>1</option>
                            <option>2</option>
                            <option>3</option>
                            <option>4</option>
                            <option>5</option>
                        </select>
                    </p>

                    <p>
                        <label>验证码：</label>
                        <input id="code" class="upt captcha" type="text" name="code"
                               v-model="code" ref="code"
                               value="" placeholder="请输入验证码,如果看不清，点击验证码进行刷新"/>
                        <img class="captcha" @click="refreshCode"
                             :src="codeUrl" />
                        <em></em>
                    </p>

                    <p><label class="btn"><a class="btn" @click="upload">提交</a></label></p>
                </form>
            </div>
        </section>
    </div>
</article>

<jsp:include page="common/footer.jsp" />
<script>


    new Vue({
        el: "#main" ,
        data: {
            codeUrl: '${pageContext.request.contextPath}/code?w=140&h=40' ,
            uploaded: false ,
            resource_name: null ,
            ext: "unknow" ,
            realExt: "" ,
            resource: null,
            progress: 0 ,
            show: true , // 显示进度条
            resourceName: null ,
            resourceDesc: null,
            score: 0 ,
            code: null ,
            showLabel: false,
            keywords: [] ,
            showType: false , // 显示分类
            types: [],
            typesChildren: [] ,
            oneTypeId: null ,
            twoTypeId: null ,
            typeName: "" ,
            size: null , //文件大小
        },
        created() {
            this.initResourceType();
        },
        methods: {

            upload(){
                // 判断 文件是否已上传
                if (this.resource == null) {
                    $(this.$refs.resource).tooltips("请选择您要上传的资源");
                    return ;
                }
                if (this.resourceName == null) {
                    $(this.$refs.resourcename).tooltips("资源名称必须录入");
                    return ;
                }

                if (this.keywords.length == 0) {
                    $(this.$refs.keywords).tooltips("至少提供一个关键字");
                    return ;
                }
                if (this.twoTypeId == null) {
                    $(this.$refs.type).tooltips("请选择资源类型");
                    return ;
                }

                if (this.code ==null) {
                    $(this.$refs.code).tooltips("请输入验证码");
                    return ;
                }

                let formdata = new FormData ;
                formdata.append("resource", this.resource);
                formdata.append("resourceName", this.resourceName);
                formdata.append("resourceDesc", this.resourceDesc) ;
                formdata.append("keywords", this.keywords.join("::"));
                formdata.append("typeId", this.twoTypeId) ;
                formdata.append("score", this.score) ;
                formdata.append("code", this.code) ;
                formdata.append("ext", this.realExt) ;
                formdata.append("size", this.size) ;
                // 提交所有的表单数据
                // 提交所有的表单数据
                fetch("${pageContext.request.contextPath}/res/uploadRes", {
                    method: "POST" ,
                    body: formdata
                }).then(ret => {
                    // 具体的消息有后台返回
                    $(this.$refs.resource).tooltips(ret.message);
                    this.codeUrl= '${pageContext.request.contextPath}/code?w=140&h=40' ;
                    this.uploaded= false ;
                    this.resource_name= null ;
                    this.ext= "unknow" ;
                    this.realExt= "" ;
                    this.resource= null;
                    this.progress= 0 ;
                    this.show= true ; // 显示进度条
                    this.resourceName= null ;
                    this.resourceDesc= null;
                    this.score= 0 ;
                    this.code= null ;
                    this.showLabel= false;
                    this.keywords= [] ;
                    this.showType= false ; // 显示分类
                    this.types= [];
                    this.typesChildren= [] ;
                    this.oneTypeId= null ;
                    this.twoTypeId= null ;
                    this.typeName= "" ;
                    this.size= null ; //文件大小
                })
            },

            refreshCode() {
                let t = new Date().getTime();
                this.codeUrl = "${pageContext.request.contextPath}/code?w=140&h=40&_=" + t ;
            },
            selectType(event){
                // 获取选中的 类型ID (二级ID)
                this.twoTypeId = event.target.value ;
                // 关闭窗口
                this.showType = false ;
                // 显示 一级分类/二级分类
                let oneType = this.types.find(type => type.id == this.oneTypeId);
                let twoType = oneType.children.find(type => type.id == this.twoTypeId) ;
                let name = oneType.typeName + "/" + twoType.typeName ;
                this.typeName = name ;
            },
            showChildrenTypes(event){
                // 获取选中的 类型的id
                let typeId = event.target.value ;
                let type = this.types.find(type => type.id == typeId) ;
                this.typesChildren = type.children ;
            },
            initResourceType(){
                fetch("${pageContext.request.contextPath}/res/types").then(ret=> {
                    this.types = ret.data ;
                    this.typesChildren = this.types[0].children ;
                    this.oneTypeId = this.types[0].id ;
                })
            },
            removeKey(index) {
                this.keywords.splice(index, 1) ;
            },
            addLabel(event){
                // 获取输入的内容，判断是否超过16个字符
                if (event.target.value == "") {
                    $(event.target).tooltips("关键字不能为空") ;
                    return ;
                }

                if (event.target.value.length > 16) {
                    $(event.target).tooltips("关键字长度过长") ;
                    return ;
                }
                // 判断 关键字是否重复
                if(this.keywords.includes(event.target.value)) {
                    $(event.target).tooltips("关键字重复") ;
                    return ;
                }

                this.keywords.push(event.target.value);
                this.showLabel = false ;
            },
            uploadFile(event) {
                this.show = true ;
                this.progress = 0 ;
                let allowExt =  ["7z", "avi", "bmp", "doc", "docx", "exe",
                    "gif", "gz", "html", "md", "mp4", "pdf",
                    "png", "ppt", "pptx", "rar", "rmvb" , "txt",
                    "wps", "xls", "xlsx", "zip"]
                // 1. 获取上传的文件
                let file = event.target.files[0] ;
                // 2. 将 uploaded设置为 true
                this.uploaded = true ;

                // 3. 获取上传的资源名称
                this.resource_name = file.name ;
                // 4. 获取 上传文件的后缀
                let ext = file.name.substring(file.name.lastIndexOf(".")+1)
                this.realExt = ext ;
                if (allowExt.includes(ext)) {
                    this.ext = ext ;
                }else{
                    this.ext = "unknow" ;
                }
                // 获取文件大小
                this.size = file.size ;

                let playing = setInterval(()=>{
                    this.progress++ ;
                    if (this.progress >= 97) {
                        clearInterval(playing)
                    }
                }, 50)
                let fm = new FormData() ;
                fm.append("resource" , file)
                // 通过 异步请求 上传 资源
                fetch("${pageContext.request.contextPath}/res/upload", {
                    method: "POST" ,
                    body: fm
                }).then(ret => {
                    if (ret.status) {
                        // ret.data 获取文件上传后的服务器地址
                        this.resource = ret.data ;
                        this.progress = 100 ;
                        // 延迟 50毫秒，关闭进度条
                        setTimeout(()=>{
                            // 关闭 进度条
                            this.show = false ;
                        }, 50);
                        this.resourceName = (this.resource_name).substring(0,(this.resource_name).indexOf("."));
                    }
                })
            }
        }
    })

</script>

</body>

</html>